#include "merchant_module.h"
#include <iostream>

// 添加菜品
bool MerchantModule::addDish(int merchant_id, const std::string& dish_name, double price) {
    // 检查菜品是否已存在
    auto merchant_it = dishes_map.find(merchant_id);
    if (merchant_it != dishes_map.end() && merchant_it->second.find(dish_name) != merchant_it->second.end()) {
        std::cerr << "Dish add failed. Dish '" << dish_name << "' already exists for merchant " << merchant_id << "." << std::endl;
        return false;
    }
    
    // 添加菜品（如果商家不存在会自动创建）
    dishes_map[merchant_id][dish_name] = price;
    std::cout << "Dish '" << dish_name << "' added successfully for merchant " << merchant_id << "." << std::endl;
    return true;
}

// 更新菜品
bool MerchantModule::updateDish(int merchant_id, const std::string& dish_name, double price) {
    auto merchant_it = dishes_map.find(merchant_id);
    if (merchant_it == dishes_map.end()) {
        std::cerr << "Dish update failed. Merchant " << merchant_id << " not found merchant id." << std::endl;
        return false;
    }
    
    auto dish_it = merchant_it->second.find(dish_name);
    if (dish_it == merchant_it->second.end()) {
        std::cerr << "Dish update failed. Dish '" << dish_name << "' not found for merchant " << merchant_id << " name." << std::endl;
        return false;
    }
    
    dish_it->second = price;
    std::cout << "Dish '" << dish_name << "' updated successfully for merchant " << merchant_id << "." << std::endl;
    return true;
}

// 删除菜品
bool MerchantModule::deleteDish(int merchant_id, const std::string& dish_name) {
    auto merchant_it = dishes_map.find(merchant_id);
    if (merchant_it == dishes_map.end()) {
        std::cerr << "Dish delete failed. Merchant " << merchant_id << " not found merchant id." << std::endl;
        return false;
    }
    
    auto dish_it = merchant_it->second.find(dish_name);
    if (dish_it == merchant_it->second.end()) {
        std::cerr << "Dish delete failed. Dish '" << dish_name << "' not found for merchant " << merchant_id << " name." << std::endl;
        return false;
    }
    
    merchant_it->second.erase(dish_it);
    
    // 如果商家没有菜品了，删除商家条目
    if (merchant_it->second.empty()) {
        dishes_map.erase(merchant_it);
        std::cout << "This merchant has no dish.Delete this merchant" << std::endl ;
    }
    
    std::cout << "Dish '" << dish_name << "' deleted successfully for merchant " << merchant_id << "." << std::endl;
    return true;
}

// 查看菜品
bool MerchantModule::viewDishes(int merchant_id, std::vector<std::string>& output_dishes) {
    auto merchant_it = dishes_map.find(merchant_id);
    if (merchant_it == dishes_map.end()) {
        std::cerr << "View dishes failed. Merchant " << merchant_id << " not found." << std::endl;
        return false;
    }
    
    for (const auto& dish : merchant_it->second) {
        output_dishes.push_back(dish.first);
    }
    
    return true;
}